package com.ruoyi.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.demo.bo.TTressQueryBo;
import com.ruoyi.demo.domain.TTress;
import com.ruoyi.demo.mapper.TTressMapper;
import com.ruoyi.demo.service.ITTressService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 古树信息列Service业务层处理
 *
 * @author ruoyi
 * @date 2021-10-31
 */
@Service
public class TTressServiceImpl extends ServicePlusImpl<TTressMapper, TTress> implements ITTressService {

    @Override
    public TTress queryById(Integer id){
        return getById(id);
    }

    @Override
    public TableDataInfo<TTress> queryPageList(TTressQueryBo bo) {
        Page<TTress> result = page(PageUtils.buildPage(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<TTress> queryList(TTressQueryBo bo) {
        return list(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<TTress> buildQueryWrapper(TTressQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TTress> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getTreeName()), TTress::getTreeName, bo.getTreeName());
        lqw.like(StrUtil.isNotBlank(bo.getTreeAlias()), TTress::getTreeAlias, bo.getTreeAlias());
        lqw.between(params.get("beginAge") != null && params.get("endAge") != null,
            TTress::getAge ,params.get("beginAge"), params.get("endAge"));
        lqw.like(StrUtil.isNotBlank(bo.getAddress()), TTress::getAddress, bo.getAddress());
        return lqw;
    }

    @Override
    public Boolean insert(TTress bo) {
        TTress add = BeanUtil.toBean(bo, TTress.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean update(TTress bo) {
        TTress update = BeanUtil.toBean(bo, TTress.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TTress entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Integer> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }
}
